﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace postSale.forms
{
    public partial class taskEdit : application.baseMasterEdit
    {
        //public override int GetFormPermission()
        //{
        //    return 7;
        //}
        public taskEdit()
        {
            try
            {
                InitializeComponent();
                myMasterSource = tasksSource;
                companyCb.LoadData();
                cbStatus.BackColor = CommonTypes.Settings.sysColorDisableBG;
                custPhoneEd.BackColor = CommonTypes.Settings.sysColorDisableBG;
                custNameEd.BackColor = CommonTypes.Settings.sysColorDisableBG;
                custAddressEd.BackColor = CommonTypes.Settings.sysColorDisableBG;
            }
            catch (Exception er)
            {
                this.ShowError(er);
            }
        }
        public common.CommonStatus[] _myValidTaskStatusList = null;
        public virtual common.CommonStatus[] myValidTaskStatusList
        {
            get { return _myValidTaskStatusList; }
            set { _myValidTaskStatusList = value; }
        }

        public myTypes.taskType[] _myValidTaskTypeList = new myTypes.taskType[] { myTypes.taskType.User_Immediate};
        public virtual myTypes.taskType[] myValidTaskTypeList 
        {
            get { return _myValidTaskTypeList; }
            set { _myValidTaskTypeList = value;}
        }

        private data.salesDS.SaleCodeDataTable _saleCodeTbl = null;
        private data.salesDS.SaleCodeDataTable mySaleCodeTbl
        {
            get
            {
                if (_saleCodeTbl == null) _saleCodeTbl = new data.salesDS.SaleCodeDataTable();
                return _saleCodeTbl;
            }
        }

        protected override void LoadData()
        {
            common.CommonStatus[] statusList = this.myValidTaskStatusList;
            myTypes.taskType[] typeList = this.myValidTaskTypeList;
            byte statusCode = 0;
            if (statusList != null)
            {
                for (int idx = 0; idx < statusList.Length; idx++)  statusCode += (byte)statusList[idx];
            }
            cbStatus.LoadList(statusList);

            byte taskTypeCode = 0;
            if (typeList != null)
            {
                for (int idx = 0; idx < typeList.Length; idx++) taskTypeCode += (byte)typeList[idx];
            }
            cbTaskType.LoadData(typeList);

            if (statusCode > 0)
                taskTA.FillByTypeStatMask(myPostSalesDS.tasks, taskTypeCode.ToString(), statusCode.ToString());
            else taskTA.FillByTypeMask(myPostSalesDS.tasks, taskTypeCode.ToString());
        }        
        protected override bool FindData() 
        {
            postSale.commonLib.myTaskFind.Find("");
            if (postSale.commonLib.myTaskFind.selectedRow == null) return true;
            data.postSaleDS.tasksRow tasksRow = postSale.commonLib.myTaskFind.selectedRow;
            myPostSalesDS.tasks.Clear();
            taskTA.FillByTaskId(myPostSalesDS.tasks,tasksRow.taskId);
            ShowCustomer();
            return true;
        }
        public override void LockEdit()
        {
            base.LockEdit();
            bool lockState = this.isLockEdit;

            companyCb.Enabled = !lockState;
            onDateEd.Enabled = !lockState;
            itemSeriEd.Enabled = !lockState;
            saleCodeEd.Enabled = (itemSeriEd.Text.Trim() == "") && !lockState;
            custCodeEd.Enabled = (saleCodeEd.Text.Trim()=="") && !lockState;
            noteEd1.Enabled = !lockState;
            noteEd2.Enabled = !lockState;
            workAddressEd.Enabled = !lockState;
            workContactEd.Enabled = !lockState;
            scheduleBtn.Enabled = !lockState;
            cbStatus.Enabled = !lockState;  //false;
            cbTaskType.Enabled = false;
        }
        protected override void SetFirstFocus() { onDateEd.Focus(); }
        protected override bool DataChangable()
        {
            if (tasksSource.Current == null) return false;
            data.postSaleDS.tasksRow taskRow = (data.postSaleDS.tasksRow)((DataRowView)tasksSource.Current).Row;
            DataRowView drTask = (DataRowView)tasksSource.Current;
            //============================
            // Check if the Order date is in working period
            //============================
            //If new Order, use the entried date, other used the original date
            if (drTask.IsNew)
            {
                if (!application.SysLibs.InWorkPeriod(onDateEd.myDateTime))
                {
                    string tmp = "[" + CommonTypes.Settings.sysWorkPeriodStart.ToShortDateString() + " - " +
                                       CommonTypes.Settings.sysWorkPeriodEnd.ToShortDateString() + "]";
                    common.SysLibs.ShowErrorMessage("Không thể thêm dữ liệu ngoài phạm vi " + tmp);
                    return false;
                }
            }
            else
            {
                DateTime onDate = (DateTime)common.SysLibs.GetOriginalData(drTask.Row, myPostSalesDS.tasks.onDateColumn.ColumnName);
                if (!application.SysLibs.InWorkPeriod(onDate))
                {
                    string tmp = "[" + CommonTypes.Settings.sysWorkPeriodStart.ToShortDateString() + " - " +
                                       CommonTypes.Settings.sysWorkPeriodEnd.ToShortDateString() + "]";
                    common.SysLibs.ShowErrorMessage("Không thể thay đổi số liệu ngoài phạm vi " + tmp);
                    return false;
                }
                common.CommonStatus tmpStatus = (common.CommonStatus)common.SysLibs.GetOriginalData(drTask.Row, myPostSalesDS.tasks.statusColumn.ColumnName);
                if (tmpStatus ==  common.CommonStatus.Completed && !application.SysLibs.isAdminLogin())
                {
                    common.SysLibs.ShowErrorMessage("Không thể thay đổi dữ liệu đã [Hoàn tất]");
                    return false;
                }
            }
            return true;
        }
        
        protected override bool DataValid(bool showMsg)
        {
            if (companyCb.myValue==common.Consts.constNullInt)
            {
                if (showMsg) common.SysLibs.ShowErrorMessage("Chưa nhập ["+companyLbl.Text+"]");
                this.companyCb.Focus();
                return false;
            }
            if (onDateEd.myDateTime == common.Consts.constNullDate)
            {
                if (showMsg) common.SysLibs.ShowErrorMessage("Chưa nhập ["+onDateLbl.Text +"]");
                this.onDateEd.Focus(); return false;
            }
            if (noteEd1.Text.Trim() == "")
            {
                if (showMsg) common.SysLibs.ShowErrorMessage("Chưa nhập [" + noteLbl1.Text + "]");
                this.noteEd1.Focus(); return false;
            }
            //if (saleCodeEd.Text.Trim()=="")
            //{
            //    if (showMsg) common.SysLibs.ShowErrorMessage("Chưa nhập ["+saleCodeLbl.Text+"]");
            //    this.saleCodeEd.Focus(); return false;
            //}
            if (custCodeEd.Text.Trim() == "")
            {
                if (showMsg) common.SysLibs.ShowErrorMessage("Chưa nhập [" + custCodeLbl.Text + "]");
                this.custCodeEd.Focus(); return false;
            }

            if (cbTaskType.myValue == myTypes.taskType.None)
            {
                if (showMsg) common.SysLibs.ShowErrorMessage("Chưa nhập [" + taskTypeLbl.Text + "]");
                this.cbTaskType.Focus(); return false;
            }
            if (cbStatus.myValue == common.CommonStatus.None)
            {
                if (showMsg) common.SysLibs.ShowErrorMessage("Chưa nhập [" + statusLbl.Text + "]");
                this.cbStatus.Focus(); return false;
            }

            return true;
        }
        public override void AddNew(string itemCode)
        {
            this.ShowMessage("");
            int saveCompany = companyCb.myValue;

            DataRowView dr = (DataRowView)tasksSource.Current;
            if ((dr == null) || (!dr.IsNew)) dr = (DataRowView)tasksSource.AddNew();

            data.postSaleDS.tasksRow row = (data.postSaleDS.tasksRow)dr.Row;
            row.taskId = "";
            row.status = (byte)common.CommonStatus.New; 
            row.onDate = DateTime.Today;
            row.createdBy = CommonTypes.Settings.sysLoginInfo.UserId;
            row.ownerId = companyCb.myValue;
            row.type = (byte)cbTaskType.myValue;

            if (saveCompany == common.Consts.constNullInt)  companyCb.SelectFirstIfNull();
            else companyCb.myValue = saveCompany;
            cbStatus.myValue = (common.CommonStatus)row.status;
            onDateEd.myDateTime = row.onDate;
            this.ShowMessage("", "<Mới>");
        }
        protected override bool UpdateData(DataRow row)
        {
            if (row == null)
            {
                taskTA.Update(myPostSalesDS.tasks);
                myPostSalesDS.tasks.AcceptChanges();
                return true; 
            }


            data.postSaleDS.tasksRow taskRow = (data.postSaleDS.tasksRow)row;
            if (taskIdEd.Text.Trim() == "")
            {
                taskIdEd.Text = application.SysLibs.GetNewAutoKey(myPostSalesDS.tasks.TableName, "", myPostSalesDS.tasks.taskIdColumn.MaxLength);
                taskRow.taskId = taskIdEd.Text; 
            }
            taskRow.EndEdit();
            taskTA.Update(taskRow);
            taskRow.AcceptChanges();

            //Disable all schedule
            if (taskRow.status == (byte)common.CommonStatus.Disabled)
            {
                postSale.dataLib.taskScheduleTA.FillByTaskId(myPostSalesDS.taskSchedule, taskRow.taskId);
                for (int idx = 0; idx < myPostSalesDS.taskSchedule.Count; idx++)
                {
                    if (myPostSalesDS.taskSchedule[idx].status == (byte)common.CommonStatus.Disabled) continue;
                    myPostSalesDS.taskSchedule[idx].status = (byte)common.CommonStatus.Disabled;
                    postSale.dataLib.taskScheduleTA.Update(myPostSalesDS.taskSchedule[idx]);
                }
                myPostSalesDS.taskSchedule.AcceptChanges();
            }
            return true;
        }
        protected override void CancelAllChanges()
        {
            myMasterSource.CancelEdit();
            myPostSalesDS.tasks.RejectChanges();
            return;
        }
        protected override bool DataChanged()
        {
            DataRowView dr = (DataRowView)myMasterSource.Current;
            if (dr == null) return false;
            DataTable changeTbl = myPostSalesDS.tasks.GetChanges();
            return (changeTbl!=null && changeTbl.Rows.Count > 0);
        }

        protected void ShowCustomer(string code)
        {
            this.custNameEd.Text = ""; this.custAddressEd.Text = ""; this.custPhoneEd.Text = ""; 
            if (code.Trim() == "") return;
            data.masterDS.CustomerRow custRow = DataAccess.DataCache.Find(myMasterDS.Customer,code);
            if (custRow == null) return;
            this.custNameEd.Text = custRow.name1;
            this.custAddressEd.Text = custRow.address1;
            if (!custRow.IsphoneNull()) this.custPhoneEd.Text = custRow.phone;

            if (myMasterSource.Current!=null)
            {
                data.postSaleDS.tasksRow tasksRow = (data.postSaleDS.tasksRow)((DataRowView)myMasterSource.Current).Row;
                if (tasksRow.IscustCodeNull() || (tasksRow.custCode.Trim() != custCodeEd.Text.Trim()) )
                    workAddressEd.Text = custAddressEd.Text;
            }
        }
        protected void ShowCustomer()
        {
            ShowCustomer(custCodeEd.Text);
        }

        private void scheduleBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (tasksSource.Current == null) return;
                data.postSaleDS.tasksRow taskRow = (data.postSaleDS.tasksRow)((DataRowView)tasksSource.Current).Row;
                if (taskRow[myPostSalesDS.taskSchedule.taskIdColumn.ToString()].ToString().Trim() == "")
                {
                    common.SysLibs.ShowErrorMessage("Xin vui lòng lưu dữ liệu trước khi thực hiện tác vụ này");
                    return;
                }
                taskScheduleTA.FillByTaskId(myPostSalesDS.taskSchedule, taskRow.taskId);
                data.postSaleDS.taskScheduleRow mainScheduleRow=null;
                for( int idx=0;idx<myPostSalesDS.taskSchedule.Count;idx++)
                {
                    if (myPostSalesDS.taskSchedule[idx].type==(byte)myTypes.scheduleType.Main)  
                    {
                        mainScheduleRow = myPostSalesDS.taskSchedule[idx];
                        break;
                    }
                }
                if (mainScheduleRow == null)
                {
                    mainScheduleRow = postSale.dataLib.AddBlankTaskSchedule(myPostSalesDS.taskSchedule, taskRow.taskId);
                    mainScheduleRow.type  = (byte)myTypes.scheduleType.Main;
                    mainScheduleRow.repeatWarnDay = 1; //Default send notifiction  for each day
                }
                mainScheduleRow.notes = taskRow.notes1;
                interfaces.myScheduleInfo.SetInfo(mainScheduleRow);
                interfaces.myScheduleInfo.ShowForm();
                if (interfaces.myScheduleInfo.myFormStatus.isCloseClick)
                {
                    mainScheduleRow.CancelEdit();
                    myPostSalesDS.taskSchedule.RejectChanges();
                    return;
                }
                interfaces.myScheduleInfo.GetInfo(mainScheduleRow);
                DateTime curDate = DataAccess.DataLibs.GetServerDateTime();
                
                //Reset the [nextRunDate] before setting new task to ensure the correct next date was selected
                DateTime saveNextRunDate = (mainScheduleRow.IsnextRunDateNull() ? common.Consts.constNullDate : mainScheduleRow.nextRunDate);
                mainScheduleRow.SetnextRunDateNull(); 
                SysLibs.SetNextRunDate(mainScheduleRow, curDate);
                //Check for pending tasks
                data.postSaleDS.tasksDataTable taskTbl = dataLib.tasksTA.GetByScheduleIdAndStatus(mainScheduleRow.scheduleId, (byte)common.CommonStatus.New);
                if ( (taskTbl.Count>0) &&
                      MessageBox.Show("Thiết lập lại sẽ hủy [" + taskTbl.Count.ToString()  + "] công việc đang chờ thực hiện ?",
                    common.Settings.sysApplicationName, MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    myPostSalesDS.taskSchedule.RejectChanges();
                    return;
                }
                //Delete all pending tasks
                postSale.dataLib.DeletePendingTask(mainScheduleRow.scheduleId, (byte)common.CommonStatus.New);

                this.Text = (mainScheduleRow.IsnextRunDateNull() ? "" : mainScheduleRow.nextRunDate.ToShortDateString());
                taskScheduleTA.Update(mainScheduleRow);
                mainScheduleRow.AcceptChanges();
            }
            catch (Exception er)
            {
                this.ShowError(er);
            }
        }
        private void saleCodeEd_Validating(object sender, CancelEventArgs e)
        {
            try
            {
                data.salesDS.SaleCodeRow saleCodeRow = DataAccess.DataCache.Find(mySaleCodeTbl, saleCodeEd.Text);
                if (saleCodeRow != null)
                {
                    custCodeEd.Text = saleCodeRow.custCode;
                }
                custCodeEd.Enabled = saleCodeEd.Text.Trim()=="" && !this.isLockEdit;
                ShowCustomer(custCodeEd.Text);
            }
            catch (Exception er)
            {
                this.ShowError(er);
            }
        }
        private void custCodeEd_Validating(object sender, CancelEventArgs e)
        {
            try
            {
                ShowCustomer(custCodeEd.Text);
            }
            catch (Exception er)
            {
                this.ShowError(er);
            }
        }
        private void tasksSource_CurrentChanged(object sender, EventArgs e)
        {
            try
            {
                this.ShowMessage("");
                ShowCustomer();
                LockEdit();
            }
            catch (Exception er)
            {
                this.ShowError(er);
            }
        }

        private void taskEdit_Load(object sender, EventArgs e)
        {
            LockEditData(true);
        }

        private void itemSeriEd_Validating(object sender, CancelEventArgs e)
        {
            try
            {
                if (itemSeriEd.Text.Trim() != "")
                {
                    //data.postSaleDS.maintenanceCardRow cardRow = postSale.dataLib.GetMaintenanceCardBySeri(itemSeriEd.Text);
                    //if (cardRow != null)
                    //{
                    //    saleCodeEd.Text = cardRow.saleCode;
                    //    custCodeEd.Text = cardRow.custCode;
                    //    ShowCustomer(custCodeEd.Text);
                    //}
                }
                LockEdit();
            }
            catch (Exception er)
            {
                this.ShowError(er);
            }
        }
    }
}
